package com.whxy02.tolearn.app.interceptor;

import com.whxy02.tolearn.app.beans.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class UserLoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 获取页面发送的存有上次访问sessionID的cookie
         * 用于验证是否在30分钟内登录过
         */

        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("sessionID")) {
                    if(redisTemplate.opsForValue().get("user:"+cookie.getValue())!=null){
                        User user= (User) redisTemplate.opsForValue().get("user:"+cookie.getValue());

                        /**
                         * 刷新存储时间
                         */
                        redisTemplate.expire("user:"+cookie.getValue(),60*60*2,TimeUnit.SECONDS);
                        request.setAttribute("user",user);
                        cookie.setMaxAge(60*60*2);
                        response.addCookie(cookie);
                        return true;
                    }
                }


            }

        }
        response.sendRedirect(request.getContextPath()+"/login.html");
        return false;
    }

}
